require 'fileutils'
require 'yaml'

class Confile
  def initialize(config_file)
    if (File.exist?(config_file))
      @confile_exists = true

      conf = YAML.load_file(config_file)

      @config_dir = conf['config_dir'] || 'config'
      @links = {}
      @files = []

      conf['links'].each do |link|
        link.each_pair do |from, to|
          @links[File.join(@config_dir, from)] = to
          @files.push(to)
        end
      end
    end
  end

  def check_confile
    if (!@confile_exists)
      puts "nothing to link! please create a Confile."
      exit 1
    end
  end

  def link
    self.check_confile

    @links.each_pair do |from, to|
      if File.exist?(from) && !File.exist?(to)
        puts "linking... #{to} -> #{from}"
        FileUtils.ln_s(from, to)
      else
        puts "skipping... #{to} -> #{from}"
      end
    end
  end

  def unlink
    self.check_confile

    @files.each do |file|
      puts "unlinking... #{file}"
      FileUtils.rm(file)
    end
  end
end
